package com.fu.shop.interceptor;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.fu.core.common.BusinessException;
import com.fu.core.common.ExceptionCode;
import com.fu.core.util.JsonUtil;
import com.fu.core.util.JwtUtil;
import com.fu.core.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 付龙江
 * @date 2022/1/30 10:43
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {
    /**
     * 拦截前处理
     *
     * @param httpServletRequest  request对象
     * @param httpServletResponse response对象
     * @param object              拦截的目标
     * @return 是否放行, true表示放行 ,false表示不放行
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        System.out.println("进入拦截器");

        String token = httpServletRequest.getHeader("token");
        // 执行认证
        if (token == null) {
            throw new BusinessException(ExceptionCode.NO_TOKEN);
        }
        // 获取 jwt 中的 phone
        String phone = null;
        try {
            phone = JwtUtil.getPhone(token);
        } catch (JWTDecodeException j) {
            throw new BusinessException(ExceptionCode.TIMEOUT_PHONE);
        }

        // 验证 token
        boolean verify = JwtUtil.verify(token, phone);
        if (!verify) {
            throw new BusinessException(ExceptionCode.NO_PHONE_AUTH);
        }
        Integer shopId = JwtUtil.getShopId(token);
        String requestURI = httpServletRequest.getRequestURI();
        System.out.println(requestURI+"---这是一个URI");

        if (shopId == null){
            throw new BusinessException(ExceptionCode.NO_STORE);
        }
        Map<String,Object> map = new HashMap<>(10);
        map.put("shopId", JwtUtil.getShopId(token));
        map.put("adminPhone",JwtUtil.getPhone(token));
        map.put("adminId",JwtUtil.getAdminId(token));
        String s = JsonUtil.objectToString(map);
        ThreadLocalUtil.setObject(s);
        System.out.println(s+"+++++++++++");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
    }
}
